package com.mj.circle;

public class CircleQueue<E> {
    //存储队头的索引
    private int front;
    private int size;
    private E[] elements;
    /**
     * 默认动态数组的初始容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    public CircleQueue() {
        this.elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    // 元素的数量
    public int size() {
        return size;
    }

    // 是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    // 清空
    public void clear() {
        for (int i = 0; i < size; i++) {
            //获取真实索引 置空
            elements[index(i)] = null;
        }
        size = 0;
        front = 0;
    }

    // 入队
    public void enQueue(E element) {
        ensureCapacity(size + 1);
        //考虑到循环的情况 入队的所在位置 (front+size)%elements.length
        elements[index(size)] = element;
        size++;
    }

    // 出队  获取队头元素
    public E deQueue() {
        E frontElement = elements[front];
        elements[front] = null;
        //考虑到循环队列 (front+1)%elements.length
        front = index(1);
        size--;
        return frontElement;
    }

    // 获取队列的头元素
    public E front() {
        return elements[front];
    }

    /**
     * 保证要有capacity的容量
     *
     * @param capacity
     */
    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (capacity <= oldCapacity) return;
        //(oldCapacity >> 1) 记得加括号 注意运算符优先级
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            //获取旧数组中的真实索引:(front + i) % elements.length
            newElements[i] = elements[index(i)];
        }
        elements = newElements;
        //重置front
        front = 0;


    }

    /**
     * 封装获取到的真实索引
     *
     * @param index
     * @return
     */
    private int index(int index) {
        index += front;
        return index - (index >= elements.length ? elements.length : 0);
    }


    @Override
    public String toString() {
        // 使用StringBuilder拼接字符串效率高一些
        StringBuilder string = new StringBuilder();
        string.append("capcacity=").append(elements.length)
                .append(" size=").append(size).append(" front=").append(front).append(", [");
        for (int i = 0; i < elements.length; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(elements[i]);
        }
        string.append("]");
        return string.toString();
    }


}
